package com.supor.aiot.mine.ui.mine;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alipay.mobile.beehive.capture.utils.Logger;
import com.android.baseconfig.base.BaseSharedPreferences;
import com.android.baseconfig.base.RxBus3;
import com.android.baseconfig.common.rxpermissions2.RxPermissions;
import com.android.baseconfig.common.utils.FileUtil;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.NetWorkUtil;
import com.android.baseconfig.common.utils.ToastUtils;
import com.android.baseconfig.common.utils.Util;
import com.android.baseconfig.common.views.AppBasicDialog;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.arouter.PathUrl;
import com.supor.aiot.common.base.BaseMVVMActivity;
import com.supor.aiot.common.entity.DictionaryBean;
import com.supor.aiot.common.entity.Result;
import com.supor.aiot.common.entity.UserInfo;
import com.supor.aiot.common.helper.ActivityHelper;
import com.supor.aiot.common.helper.EditTextLengthHelper;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.aiot.common.helper.RefreshHelper;
import com.supor.aiot.common.helper.WsHelper;
import com.supor.aiot.common.utils.BitmapUtil;
import com.supor.aiot.mine.R;
import com.supor.aiot.mine.bean.Dictionary;
import com.supor.aiot.mine.databinding.ActivityMineAccountBinding;
import com.supor.aiot.mine.ui.adapter.DictionaryAdapter;
import com.supor.aiot.mine.utils.TakePhotoPop;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import androidx.core.content.FileProvider;

import static android.content.ContentValues.TAG;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2021, by het, ShenZhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: 个人信息 <br>
 * 作者: lei <br>
 * 日期: 2021/10/15 <br>
 */
@Route(path = PathUrl.PATH_MINE_ACCOUNT)
public class MineAccountActivity extends BaseMVVMActivity<MineAccountViewModel, ActivityMineAccountBinding> {

    private static final int ASPECT_X = 1;
    private static final int ASPECT_Y = 1;
    private static final String CLIP_PHOTO = "com.android.camera.action.CROP";
    private static final String DATA = "data";
    private static final String IMAGE_URI = "image/*";
    private static final int OUTPUT_X = 220;
    private static final int OUTPUT_Y = 220;
    private static final String PHPTO_TEMP_NAME = "head_temp.png";
    private static final int REQUEST_CODE_CAMERA = 10;
    private static final int REQUEST_CODE_PHOTO = 11;
    private static final int REQUEST_CODE_CLIPIMAGE = 12;
    List<Dictionary> dictionaryList = new ArrayList<>();
    private DictionaryAdapter ageAdapter;
    int selectPos = -1;
    File tempFile;
    private String localHead;
    private boolean hasHeadUrl;
    private RxPermissions rxPermissions;
    private AppBasicDialog commonDialog;

    @Override
    protected int resourceId() {
        return R.layout.activity_mine_account;
    }

    @Override
    protected void initView() {
        super.initView();
        bindingView.setViewM(this);
        bindingView.toolbar.setIvLeftOnClickListener(v -> finish());
        bindingView.toolbar.setTvLeftOnClickListener(v -> finish());
        bindingView.toolbar.setTvRightOnClickListener(v -> {
            viewModel.logout();
        });

        // age
        RefreshHelper.initGrid(bindingView.rcvAge, 4,
                getResources().getDimensionPixelSize(R.dimen.dp_9),
                getResources().getDimensionPixelSize(R.dimen.dp_6));

        ageAdapter = new DictionaryAdapter(dictionaryList);
        bindingView.rcvAge.setOnItemClickListener((v, position) -> {
            Logc.e("onItemClick: position: " + position);
            List<Dictionary> list = ageAdapter.getData();
            if (selectPos != -1 && selectPos != position) {
                list.get(selectPos).isSelect = false;
                ageAdapter.notifyItemChanged(selectPos);
            }
            Dictionary dictionary = list.get(position);
            dictionary.isSelect = !dictionary.isSelect;
            ageAdapter.notifyItemChanged(position);
            selectPos = position;
        });
        bindingView.rcvAge.setAdapter(ageAdapter);
        if (null != GlobalDataCache.userInfo) {
            bindingView.etName.setText(GlobalDataCache.userInfo.getNickName());
            String headUrl = GlobalDataCache.userInfo.getFaceImage();
            setImage(headUrl);
            String sex = GlobalDataCache.userInfo.getSex();
            if (!TextUtils.isEmpty(sex)) {
                if (getString(R.string.male).equalsIgnoreCase(sex)) {
                    bindingView.ivMale.setSelected(true);
                } else if (getString(R.string.female).equalsIgnoreCase(sex)) {
                    bindingView.ivFemale.setSelected(true);
                }
            }
        }
        bindingView.etName.setFilters(new InputFilter[]{EditTextLengthHelper.getInstance().lengthResult(20)});

        TakePhotoPop.getInstance().init(this, (v, position) -> {
            if (position == 1) {
                gotoCamera();
            } else if (position == 2) {
                gotoGallery();
            }
        });
    }

    @Override
    protected void initData() {

        // JSONObject jo = new JSONObject();
        // // 分享类型：0取消分享；1微信；2微信朋友圈；3 QQ好友；4 QQ空间；5微博；6支付宝；7抖音
        // jo.put(Constants.Key.param_shareType, 1);
        // // 分享方式：0x1-text，0x2-image，0x3-URL
        // jo.put(Constants.Key.param_type, 3);
        // // 分享标题
        // jo.put(Constants.Key.param_title, "排骨汤蒸玉米");
        // // 分享内容描述
        // jo.put(Constants.Key.param_desc, "家常萝卜排骨汤搭配蒸玉米，肉质蛋白与膳食纤维的营养搭配，齐活儿了。");
        // // URL连接
        // jo.put(Constants.Key.param_path, "https://i.supor.com/supor-food-ui/protocol/share-supor/#/pages/detailOfRecipe/detailOfRecipe?code=2FF48DB4E0D45E44A411221C9F7680E25CB85D1C26C76F26ED2E9C94E8E9B983D3A75A475A861C87085E5513296EB0E024038811DFD56C3D225E7E7B58EA0BD7");
        // // 分享图片使用 URL（imgUrl）
        // jo.put(Constants.Key.param_imageUrl, "");
        // // 自定义分享预览大图
        // jo.put(Constants.Key.param_bgImgUrl, "https://iot-video.supor.com/image/cover/3E87754C161F4DAFA594BB8DDF14441F-6-2.jpg");
        //
        // SharePopUtils.getInstance()
        //         .showWechat(true)
        //         .showWeibo(true)
        //         .showDouyin(true)
        //         .params(jo)
        //         .initPop(this);

        rxPermissions = new RxPermissions(this);
        // 年代字典
        viewModel.getAgeData().observe(this, result -> {
            if (result instanceof Result.Success) {
                List<DictionaryBean> list = (List<DictionaryBean>) result.getData();
                String ages = GlobalDataCache.userInfo.getChronology();
                for (int i = 0; i < list.size(); i++) {
                    DictionaryBean s = list.get(i);
                    Dictionary dictionary = new Dictionary();
                    if (s.getSysCodeSub().equalsIgnoreCase(ages)) {
                        dictionary.isSelect = true;
                        selectPos = i;
                    }
                    dictionary.dictionaryBean = s;
                    dictionaryList.add(dictionary);
                }

                ageAdapter.setList(dictionaryList);
            } else if (result instanceof Result.Error) {
                if (NetWorkUtil.getConnectionType(AppAgent.getApp()) == 0) {
                    showError();
                } else {
                    ToastUtils.getInstance().showCustomToast("年代信息获取失败");
                }
            }
        });

        viewModel.getAgeList();

        viewModel.getUploadResult().observe(this, result -> {
            if (result instanceof Result.Error) {
                ToastUtils.getInstance().showCustomToast("上传头像失败: " + ((Result.Error) result).getErrorMsg());
            }
        });

        viewModel.getUpdateResult().observe(this, result -> {
            closeLoading();
            if (result instanceof Result.Success) {
                ToastUtils.getInstance().showCustomToast("个人信息保存成功");
                finish();
            } else if (result instanceof Result.Error) {
                ToastUtils.getInstance().showCustomToast("个人信息保存失败: " + ((Result.Error) result).getErrorMsg());
            }
        });

        viewModel.getLogoutResult().observe(this, result -> {
            if (result instanceof Result.Success) {
                ToastUtils.getInstance().showCustomToast("退出登录成功");
                BaseSharedPreferences.setString(AppAgent.getApp(), Constants.Key.USER_INFO, "");
                GlobalDataCache.userInfo = null;
                GlobalDataCache.deviceTree = null;
                AppAgent.setLogin(false);
                WsHelper.getInstance().exit();
                RxBus3.getInstance().post(Constants.Tag.LOGOUT, Constants.Value.SUCCESS);
                finish();
            } else if (result instanceof Result.Error) {
                ToastUtils.getInstance().showCustomToast("退出登录失败: " + ((Result.Error) result).getErrorMsg());
            }
        });
    }

    /**
     * 设置用户头像，4个默认头像本地做存储，分别对应用户信息faceImage字段"1""2""3""4"
     *
     * @param headUrl 1|2|3|4|url|本地路径
     */
    private void setImage(String headUrl) {
        bindingView.ivHead1Check.setVisibility(View.GONE);
        bindingView.ivHead2Check.setVisibility(View.GONE);
        bindingView.ivHead3Check.setVisibility(View.GONE);
        bindingView.ivHead4Check.setVisibility(View.GONE);
        bindingView.ivHead5Check.setVisibility(View.GONE);
        bindingView.tvChange.setVisibility(View.GONE);

        if (TextUtils.isEmpty(headUrl)) {
            headUrl = "1";
        }
        if ("1".equalsIgnoreCase(headUrl)) {
            bindingView.ivHead1Check.setVisibility(View.VISIBLE);
        } else if ("2".equalsIgnoreCase(headUrl)) {
            bindingView.ivHead2Check.setVisibility(View.VISIBLE);
        } else if ("3".equalsIgnoreCase(headUrl)) {
            bindingView.ivHead3Check.setVisibility(View.VISIBLE);
        } else if ("4".equalsIgnoreCase(headUrl)) {
            bindingView.ivHead4Check.setVisibility(View.VISIBLE);
        } else {
            if (headUrl.startsWith("http")) {
                BitmapUtil.loadUrl(headUrl, bindingView.ivHead5, BitmapUtil.options4);
            } else {
                BitmapUtil.loadLocal(headUrl, bindingView.ivHead5, BitmapUtil.options4);
            }
            bindingView.ivHead5Check.setVisibility(View.VISIBLE);
            bindingView.tvChange.setVisibility(View.VISIBLE);
            hasHeadUrl = true;
        }
    }

    public void click(View view) {
        int id = view.getId();
        if (id == R.id.rl_head1) {
            setImage("1");
            localHead = "1";
        } else if (id == R.id.rl_head2) {
            setImage("2");
            localHead = "2";
        } else if (id == R.id.rl_head3) {
            setImage("3");
            localHead = "3";
        } else if (id == R.id.rl_head4) {
            setImage("4");
            localHead = "4";
        } else if (id == R.id.rl_head5) {
            // 如果第5个头像有值，需要加选中状态判断
            if (hasHeadUrl) {
                bindingView.ivHead1Check.setVisibility(View.GONE);
                bindingView.ivHead2Check.setVisibility(View.GONE);
                bindingView.ivHead3Check.setVisibility(View.GONE);
                bindingView.ivHead4Check.setVisibility(View.GONE);
                if (bindingView.ivHead5Check.getVisibility() == View.GONE) {
                    bindingView.ivHead5Check.setVisibility(View.VISIBLE);
                    bindingView.tvChange.setVisibility(View.VISIBLE);
                } else {
                    TakePhotoPop.getInstance().showPhotoPop(this, bindingView.llRoot);
                }
            } else {
                TakePhotoPop.getInstance().showPhotoPop(this, bindingView.llRoot);
            }
        } else if (id == R.id.iv_male) {
            bindingView.ivMale.setSelected(!bindingView.ivMale.isSelected());
            bindingView.ivFemale.setSelected(false);
        } else if (id == R.id.iv_female) {
            bindingView.ivMale.setSelected(false);
            bindingView.ivFemale.setSelected(!bindingView.ivFemale.isSelected());
        } else if (id == R.id.btn_save) {
            UserInfo oldUser = GlobalDataCache.userInfo;
            UserInfo userInfo = oldUser.clone();
            if (!TextUtils.isEmpty(localHead)) {
                userInfo.setFaceImage(localHead);
            }
            String name = bindingView.etName.getInputText();
            if (TextUtils.isEmpty(name)) {
                ToastUtils.getInstance().showCustomToast("用户昵称不能为空");
                return;
            }
            userInfo.setNickName(name);
            Dictionary selectAge = null;
            List<Dictionary> ageList = ageAdapter.getData();
            for (Dictionary dictionary : ageList) {
                if (dictionary.isSelect) {
                    selectAge = dictionary;
                    break;
                }
            }
            if (selectAge != null) {
                userInfo.setChronology(selectAge.dictionaryBean.getSysCodeSub());
            } else {
                ToastUtils.getInstance().showCustomToast("请选择年代");
                return;
            }
            if (bindingView.ivMale.isSelected()) {
                userInfo.setSex("男");
            } else if (bindingView.ivFemale.isSelected()) {
                userInfo.setSex("女");
            } else {
                ToastUtils.getInstance().showCustomToast("请选择性别");
                return;
            }
            if (TextUtils.isEmpty(oldUser.getFaceImage())
                    || !oldUser.getFaceImage().equalsIgnoreCase(userInfo.getFaceImage())
                    || !oldUser.getNickName().equalsIgnoreCase(userInfo.getNickName())
                    || (TextUtils.isEmpty(oldUser.getChronology()) && !TextUtils.isEmpty(userInfo.getChronology()))
                    || (!TextUtils.isEmpty(oldUser.getChronology()) && !oldUser.getChronology().equalsIgnoreCase(userInfo.getChronology()))
                    || (TextUtils.isEmpty(oldUser.getSex()) && !TextUtils.isEmpty(userInfo.getSex()))
                    || (!TextUtils.isEmpty(oldUser.getSex()) && !oldUser.getSex().equalsIgnoreCase(userInfo.getSex()))) {

                showLoading();
                if (localHead != null && localHead.length() > 1) {
                    viewModel.uploadPhoto(userInfo);
                    return;
                }
                viewModel.updateUser(userInfo);
            } else {
                Logc.e("click: user not update");
                finish();
            }
        }
    }

    @Override
    public void updateNetStatus(int type) {
        super.updateNetStatus(type);
    }

    @SuppressLint({"CheckResult", "AutoDispose"})
    private void gotoCamera() {
        rxPermissions.request(Manifest.permission.CAMERA)
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                .subscribe(aboolean -> {
                                    if (aboolean) {
                                        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                                        if (Util.isSdcardExist()) {
                                            createTempFile();
                                            Uri photoURI = FileProvider.getUriForFile(MineAccountActivity.this,
                                                    "com.supor.aiot.fileprovider", tempFile);
                                            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                                            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                                        }
                                        startActivityForResult(intent, REQUEST_CODE_CAMERA);
                                    } else {
                                        Logc.i("permission request: failed");
                                        showFailedDialog(2);
                                    }
                                });
                    } else {
                        Logc.i("permission request: failed");
                        showFailedDialog(1);
                    }
                });
    }

    @SuppressLint({"CheckResult", "AutoDispose"})
    private void gotoGallery() {
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(aboolean -> {
                    if (aboolean) {
                        createTempFile();
                        Intent intent = new Intent("android.intent.action.PICK",
                                MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                        startActivityForResult(intent, REQUEST_CODE_PHOTO);
                    } else {
                        Logc.i("permission request: failed");
                        showFailedDialog(2);
                    }
                });
    }

    private void createTempFile() {
        String filePath = FileUtil.getExternalStoragePath() + "/Download/苏泊尔/" + PHPTO_TEMP_NAME;
        FileUtil.createDirs(FileUtil.getExternalStoragePath() + "/Download/苏泊尔");
        tempFile = new File(filePath);
        if (tempFile.exists()) {
            tempFile.delete();
        }
        try {
            tempFile.createNewFile();
        } catch (IOException ex) {
            Logger.error(TAG, "Create file occur an IOException");
        }
    }

    protected void showFailedDialog(int type) {
        if (commonDialog != null && commonDialog.isShowing()) {
            commonDialog.dismiss();
        }
        AppBasicDialog.Builder builder = new AppBasicDialog.Builder(this, false);
        if (type == 1) {
            builder.setTitle(R.string.permission_camera_title);
            builder.setMessage(R.string.permission_camera_msg);
        } else if (type == 2) {
            builder.setTitle(R.string.permission_storage_title);
            builder.setMessage(R.string.permission_storage_msg);
        }
        builder.setNegativeButton(R.string.cancel, (dialog, which) -> {
            dialog.dismiss();
        });
        builder.setPositiveButton(R.string.go_settings, (dialog, which) -> {
            ActivityHelper.startAppSettings(this, Constants.REQUEST_CODE);
            dialog.dismiss();
        });
        commonDialog = builder.create();
        commonDialog.setCancelable(false);
        commonDialog.show();
    }

    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CAMERA) {
            if (resultCode == -1 && Util.isSdcardExist()) {
                Logc.d("REQUEST_CODE_CAMERA tempFile = " + this.tempFile.getAbsolutePath());
                startPhotoZoom(this.tempFile);
            }
        } else if (requestCode == REQUEST_CODE_PHOTO) {
            if (resultCode == -1 && data != null) {
                Logc.d("REQUEST_CODE_PHOTO tempFile = " + (tempFile != null ?
                        tempFile.getAbsolutePath() : "null"));
                startPhotoZoom(data.getData());
            }
        } else if (requestCode == REQUEST_CODE_CLIPIMAGE) {
            Logc.d("REQUEST_CODE_CLIPIMAGE tempFile = " + (tempFile != null ?
                    tempFile.getAbsolutePath() : "null"));
            if (data != null) {
                setSavePhoto(data);
            }

        }
    }

    public void setSavePhoto(Intent intent) {
        Logc.d("setSavePhoto: start");
        if (null != tempFile && tempFile.exists()) {
            String path = tempFile.getAbsolutePath();
            Logc.d("tempFile.size = " + tempFile.length());
            // 头像压缩在200K内
            if (tempFile.length() > 200 * 1024) {
                Bitmap bitmap = BitmapFactory.decodeFile(path);
                if (bitmap != null) {
                    Bitmap tempBitmap = BitmapUtil.compressImage(200, bitmap);
                    BitmapUtil.saveImage(tempBitmap, path);
                    Logc.d("tempFile.compress.size = " + tempFile.length());
                }
            }
            Logc.d("setSavePhoto: end");
            setImage(path);
            localHead = path;
        }
    }

    public void startPhotoZoom(Uri uri) {
        Logc.d("uri = " + uri);
        Intent intent = new Intent(CLIP_PHOTO);
        intent.setDataAndType(uri, IMAGE_URI);// uri是已经选择的图片Uri
        intent.putExtra("crop", true);
        intent.putExtra("aspectX", ASPECT_X);// 裁剪框比例
        intent.putExtra("aspectY", ASPECT_Y);
        intent.putExtra("outputX", OUTPUT_X);// 输出图片大小
        intent.putExtra("outputY", OUTPUT_Y);
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra("return-data", false);
        try {
            if (Util.isSdcardExist()) {
                if (null == tempFile || !tempFile.exists()) {
                    String filePath =
                            FileUtil.getExternalStoragePath() + "/Download/苏泊尔/" + PHPTO_TEMP_NAME;
                    FileUtil.createDirs(FileUtil.getExternalStoragePath() + "/Download/苏泊尔");
                    tempFile = new File(filePath);
                }
                intent.putExtra("output", Uri.fromFile(tempFile));  // 指定目标文件
            }
            intent.putExtra("outputFormat", "JPEG");//输出文件格式
            this.startActivityForResult(intent, REQUEST_CODE_CLIPIMAGE);
        } catch (Exception e) {
            e.printStackTrace();
            Logc.e("e = " + e);
        }
    }

    public void startPhotoZoom(File file) {
        Logc.d("file = " + file.getAbsolutePath());
        Intent intent = new Intent(CLIP_PHOTO);
        Uri photoURI;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

            /* getUriForFile(Context context, String authority, File file):此处的authority需要和manifest里面保持一致。
            photoURI打印结果：content://com.supor.aiot.fileProvider/camera_photos/temp_photo.jpg
            这里的camera_photos:对应filepaths.xml中的name
            */
            photoURI = FileProvider.getUriForFile(this, "com.supor.aiot.fileprovider", file);

            /* 这句要记得写：这是申请权限，之前因为没有添加这个，打开裁剪页面时，一直提示“无法修改低于50*50像素的图片”，
            开始还以为是图片的问题呢，结果发现是因为没有添加FLAG_GRANT_READ_URI_PERMISSION。
            如果关联了源码，点开FileProvider的getUriForFile()看看（下面有），注释就写着需要添加权限。
            */
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            photoURI = Uri.fromFile(file);
        }
        Logc.d("photoURI = " + photoURI);
        intent.setDataAndType(photoURI, IMAGE_URI);// uri是已经选择的图片Uri
        intent.putExtra("crop", true);
        intent.putExtra("aspectX", ASPECT_X);// 裁剪框比例
        intent.putExtra("aspectY", ASPECT_Y);
        intent.putExtra("outputX", OUTPUT_X);// 输出图片大小
        intent.putExtra("outputY", OUTPUT_Y);
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra("return-data", false);
        try {
            if (Util.isSdcardExist()) {
                if (null == tempFile || !tempFile.exists()) {
                    String filePath =
                            FileUtil.getExternalStoragePath() + "/Download/苏泊尔/" + PHPTO_TEMP_NAME;
                    FileUtil.createDirs(FileUtil.getExternalStoragePath() + "/Download/苏泊尔");
                    tempFile = new File(filePath);
                }
                intent.putExtra("output", Uri.fromFile(tempFile));  // 指定目标文件
            }
            intent.putExtra("outputFormat", "JPEG");//输出文件格式
            this.startActivityForResult(intent, REQUEST_CODE_CLIPIMAGE);
        } catch (Exception e) {
            e.printStackTrace();
            Logc.e("e = " + e);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (tempFile != null && tempFile.exists()) {
            tempFile.delete();
        }
    }
}
